package com.macro.mall.tiny.modules.basic;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.basic.model.MemberIncreaseData;
import com.macro.mall.tiny.modules.basic.model.OrderIncreaseData;
import com.macro.mall.tiny.modules.oms.mapper.OmsOrderMapper;
import com.macro.mall.tiny.modules.oms.model.OmsOrder;
import com.macro.mall.tiny.modules.oms.service.OmsOrderService;
import com.macro.mall.tiny.modules.oms.service.impl.OmsOrderServiceImpl;
import com.macro.mall.tiny.modules.ums.mapper.UmsMemberMapper;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.bean.validators.plugins.schema.NotNullAnnotationPlugin;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Tyrone
 * @date 2024/11/17 13:12
 */

@RestController
@RequestMapping("/basic/indexData")
@Api(tags = "IndexDataController", description = "首页数据管理")
@Tag(name = "IndexDataController", description = "首页数据管理")
public class IndexDataController {

    @Autowired
    private OmsOrderMapper omsOrderMapper;

    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private OmsOrderServiceImpl omsOrderServiceImpl;

    @Autowired
    private UmsMemberMapper umsMemberMapper;


    @ApiOperation("获取会员增长数据")
    @GetMapping("/getMemberIncreaseData")
    public CommonResult<MemberIncreaseData> getMemberIncreaseData(@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                  @RequestParam(required = false) Date startDate,
                                                                  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                  @RequestParam(required = false) Date endDate) {

        long todayIncrease = umsMemberService.count(new QueryWrapper<>(new UmsMember())
                .ge("create_time", DateUtil.beginOfDay(new Date())).le("create_time", DateUtil.endOfDay(new Date())));
        long yesterdayIncrease = umsMemberService.count(new QueryWrapper<>(new UmsMember())
                .ge("create_time", DateUtil.beginOfDay(DateUtil.yesterday())).le("create_time", DateUtil.endOfDay(DateUtil.yesterday())));
        long currentMonthlyIncrease = umsMemberService.count(new QueryWrapper<>(new UmsMember())
                .ge("create_time", DateUtil.beginOfMonth(new Date())).le("create_time", DateUtil.endOfMonth(new Date())));
        long total = umsMemberService.count(new QueryWrapper<>(new UmsMember()));

        List<Map<String, Object>> dailyIncreaseData = umsMemberService.getDailyIncreaseData(startDate, endDate, null);

        List<Map<String, Object>> dailyMemberIncrease = new ArrayList<>();
        Map<String, Integer> memberIncreaseMap = dailyIncreaseData.stream()
                .collect(Collectors.toMap(
                        item -> item.get("days").toString(),
                        item -> Integer.parseInt(item.get("count").toString())
                ));

        Date currentDate = startDate;
        while (!currentDate.after(endDate)) {
            String dateStr = DateUtil.formatDateTime(currentDate);
            Map<String, Object> item = new HashMap<>();
            item.put("days", DateUtil.formatDate(currentDate));
            item.put("count", memberIncreaseMap.getOrDefault(dateStr, 0));
            dailyMemberIncrease.add(item);
            currentDate = DateUtil.offsetDay(currentDate, 1);
        }

        MemberIncreaseData memberIncreaseData = new MemberIncreaseData();
        memberIncreaseData.setTodayMemberIncrease((int) todayIncrease);
        memberIncreaseData.setYesterdayMemberIncrease((int) yesterdayIncrease);
        memberIncreaseData.setCurrentMonthlyMemberIncrease((int) currentMonthlyIncrease);
        memberIncreaseData.setDailyMemberIncrease(dailyMemberIncrease);
        memberIncreaseData.setTotal((int) total);

        return CommonResult.success(memberIncreaseData);
    }


    @ApiOperation("获取VIP增长数据")
    @GetMapping("/getMemberVIPIncreaseData")
    public CommonResult<MemberIncreaseData> getMemberVIPIncreaseData(@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                     @RequestParam(required = false) Date startDate,
                                                                     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                     @RequestParam(required = false) Date endDate) {

        long todayIncrease = omsOrderServiceImpl.count(new QueryWrapper<OmsOrder>()
                .select("DISTINCT open_id") // 选择唯一的 open_id
                .eq("status", 1)
                .ge("pay_time", DateUtil.beginOfDay(new Date()))
                .le("pay_time", DateUtil.endOfDay(new Date())));

        long yesterdayIncrease = omsOrderServiceImpl.count(new QueryWrapper<OmsOrder>()
                .select("DISTINCT open_id") // 选择唯一的 open_id
                .eq("status", 1)
                .ge("pay_time", DateUtil.beginOfDay(DateUtil.yesterday()))
                .le("pay_time", DateUtil.endOfDay(DateUtil.yesterday())));

        long currentMonthlyIncrease = omsOrderServiceImpl.count(new QueryWrapper<OmsOrder>()
                .select("DISTINCT open_id") // 选择唯一的 open_id
                .eq("status", 1)
                .ge("pay_time", DateUtil.beginOfMonth(new Date()))
                .le("pay_time", DateUtil.endOfMonth(new Date())));

        long total = umsMemberService.count(new QueryWrapper<>(new UmsMember()).eq("vip", 1));

        List<Map<String, Object>> dailyIncreaseData = omsOrderMapper.getVipDailyIncreaseData(startDate, endDate);
//        List<Map<String, Object>> dailyIncreaseData = umsMemberService.getDailyIncreaseData(startDate, endDate, 1);

        List<Map<String, Object>> dailyMemberIncrease = new ArrayList<>();
        Map<String, Integer> memberIncreaseMap = dailyIncreaseData.stream()
                .collect(Collectors.toMap(
                        item -> item.get("days").toString(),
                        item -> Integer.parseInt(item.get("count").toString())
                ));

        Date currentDate = startDate;
        while (!currentDate.after(endDate)) {
            String dateStr = DateUtil.format(currentDate, "yyyy-MM-dd 00:00:00");
            Map<String, Object> item = new HashMap<>();
            item.put("days", DateUtil.formatDate(currentDate));
            item.put("count", memberIncreaseMap.getOrDefault(dateStr, 0));
            dailyMemberIncrease.add(item);
            currentDate = DateUtil.offsetDay(currentDate, 1);
        }


        MemberIncreaseData memberIncreaseData = new MemberIncreaseData();
        memberIncreaseData.setDailyMemberIncrease(dailyMemberIncrease);
        memberIncreaseData.setTodayMemberIncrease((int) todayIncrease);
        memberIncreaseData.setYesterdayMemberIncrease((int) yesterdayIncrease);
        memberIncreaseData.setCurrentMonthlyMemberIncrease((int) currentMonthlyIncrease);
        memberIncreaseData.setTotal((int) total);

        return CommonResult.success(memberIncreaseData);
    }


    @ApiOperation("获取订单增长数据")
    @GetMapping("/getOrderIncreaseData")
    public CommonResult<OrderIncreaseData> getOrderIncreaseData(@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                @RequestParam(required = false) Date startDate,
                                                                @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
                                                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                                                @RequestParam(required = false) Date endDate) {
        OrderIncreaseData orderIncreaseData = omsOrderMapper.countBasicOrderData();
        if (orderIncreaseData == null) orderIncreaseData = new OrderIncreaseData();
        List<Map<String, Object>> dailyOrderNum = omsOrderMapper.countDailyOrderNum(startDate, endDate);
        List<Map<String, Object>> dailyOrderIncome = omsOrderMapper.countDailyOrderIncome(startDate, endDate, null);

        List<OrderIncreaseData.OrderIncreaseItem> dailyOrderIncrease = new ArrayList<>();
        Map<String, Integer> orderNumMap = dailyOrderNum.stream()
                .collect(Collectors.toMap(
                        item -> item.get("days").toString(),
                        item -> Integer.parseInt(item.get("count").toString())
                ));
        Map<String, Integer> orderIncomeMap = dailyOrderIncome.stream()
                .collect(Collectors.toMap(
                        item -> item.get("days").toString(),
                        item -> Integer.parseInt(item.get("count").toString())
                ));

        Date currentDate = startDate;
        while (!currentDate.after(endDate)) {
            String dateStr = DateUtil.format(currentDate, "yyyy-MM-dd 00:00:00");
            OrderIncreaseData.OrderIncreaseItem item = new OrderIncreaseData.OrderIncreaseItem();
            item.setDate(currentDate);
            item.setOrderCount(orderNumMap.getOrDefault(dateStr, 0));
            item.setOrderAmount(orderIncomeMap.getOrDefault(dateStr, 0));
            dailyOrderIncrease.add(item);
            currentDate = DateUtil.offsetDay(currentDate, 1);
        }


        orderIncreaseData.setDailyOrderIncrease(dailyOrderIncrease);


        return CommonResult.success(orderIncreaseData);
    }


    public static void main(String[] args) {
        System.out.println(DateUtil.beginOfDay(new Date()));
        System.out.println(DateUtil.endOfDay(new Date()));
    }


}
